﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.DataAccess;
using StockFinder.Model;

namespace StockFinder.Services.PriceDatabaseAnalysers
{
    public class ThreeWeeksTightPriceDatabaseAnalyser
    {
        public PriceDatabaseAnalyserResult AnalysePrices(List<DailyPrice> prices)
        {
            var result = new PriceDatabaseAnalyserResult();

            var orderedPrices = prices.OrderByDescending(p => p.PriceDate);

            var weeklyPrices = orderedPrices.AsWeeklyPrices();

            //need at least 3 weeks
            if (weeklyPrices.Count() >= 3)
            {
                decimal week1Close = weeklyPrices.ElementAt(0).GetWeeklyClose();
                decimal week2Close = weeklyPrices.ElementAt(1).GetWeeklyClose();
                decimal week3Close = weeklyPrices.ElementAt(2).GetWeeklyClose();

                decimal week3Differential = week3Close / 100;

                if ((week2Close <= (week3Close + week3Differential)) &&
                    (week2Close >= (week3Close - week3Differential)))
                {
                    decimal week2Differential = week2Close / 100;

                    if ((week1Close <= (week2Close + week2Differential)) &&
                        (week1Close >= (week2Close - week2Differential)))
                    {
                        //then we have 3 weeks tight
                        result.Succeeded = true;

                        DailyPrice lastPrice = prices.ElementAt(0);
                        result.DaysOfPrices = prices.Count();

                        decimal sma50 = orderedPrices.GetSimpleMovingAverage(50);

                        if (sma50 > 0)
                        {
                            decimal percentFromSMA50 = lastPrice.AdjustedClose - sma50;

                            percentFromSMA50 = (percentFromSMA50 / sma50) * 100;

                            result.PercentFromSMA50 = percentFromSMA50;
                        }
                    }
                }
            }

            return result;
        }        
    }
}
